# app/services/external_api.py

import aiohttp
import asyncio
import logging
import json
import time
import requests
from app.core.config import settings

async def forward_request_to_external_api(data):
    headers = {
        'Content-Type': settings.CONTENT_TYPE,
        'Authorization': settings.AUTHORIZATION
    }

    data_to_send = data.copy()
    data_to_send.pop('name_id', None)

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(settings.EXTERNAL_API_URL, json=data_to_send, headers=headers, timeout=30) as response:
                response_data = await response.json()
                logging.info(f"外部 API 响应：{response_data}")
                return response_data, response.status
        except aiohttp.ClientError as e:
            logging.error(f"请求异常：{e}")
            return {'error': f'Request exception occurred: {e}'}, 500
        except asyncio.TimeoutError:
            logging.error("请求超时")
            return {'error': 'Request timed out'}, 504

async def create_voice(voice_type):
    headers = {
        'Content-Type': settings.CONTENT_TYPE,
        'Authorization': settings.AUTHORIZATION
    }
    payload = {'type': voice_type}
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(settings.EXTERNAL_CREATE_VOICE_URL, json=payload, headers=headers, timeout=30) as response:
                response_data = await response.json()
                logging.info(f"外部 API create_voice 响应：{response_data}")
                return response_data, response.status
        except aiohttp.ClientError as e:
            logging.error(f"请求 create_voice 异常：{e}")
            return {'error': f'Request exception occurred: {e}'}, 500
        except asyncio.TimeoutError:
            logging.error("请求 create_voice 超时")
            return {'error': 'Request timed out'}, 504

async def train_voice(voice_id, audio_url, voice_type):
    headers = {
        'Content-Type': settings.CONTENT_TYPE,
        'Authorization': settings.AUTHORIZATION
    }
    payload = {
        'voice_id': voice_id,
        'audio_url': audio_url,
        'voice_type': voice_type
    }
    timeout = aiohttp.ClientTimeout(total=300)  # 设置超时时间为300秒
    async with aiohttp.ClientSession(timeout=timeout) as session:
        try:
            async with session.post(settings.EXTERNAL_TRAIN_VOICE_URL, json=payload, headers=headers) as response:
                response_data = await response.json()
                logging.info(f"外部 API train_voice 响应：{response_data}")
                return response_data, response.status
        except aiohttp.ClientError as e:
            logging.error(f"请求 train_voice 异常：{e}")
            return {'error': f'Request exception occurred: {e}'}, 500
        except asyncio.TimeoutError:
            logging.error("请求 train_voice 超时")
            return {'error': 'Request timed out'}, 504

async def confirm_voice(voice_id, title, voice_type):
    headers = {
        'Content-Type': settings.CONTENT_TYPE,
        'Authorization': settings.AUTHORIZATION
    }
    payload = {
        'voice_id': voice_id,
        'title': title,
        'voice_type': voice_type
    }
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(settings.EXTERNAL_CONFIRM_VOICE_URL, json=payload, headers=headers, timeout=30) as response:
                response_data = await response.json()
                logging.info(f"外部 API confirm_voice 响应：{response_data}")
                return response_data, response.status
        except aiohttp.ClientError as e:
            logging.error(f"请求 confirm_voice 异常：{e}")
            return {'error': f'Request exception occurred: {e}'}, 500
        except asyncio.TimeoutError:
            logging.error("请求 confirm_voice 超时")
            return {'error': 'Request timed out'}, 504

async def list_voices():
    """
    调用外部API获取声音列表。
    GET请求: https://hfw-api.lingverse.co/api/v1/hifly/voice/list
    Headers和其他外部请求接口一致，Body不需要。
    """
    headers = {
        'Content-Type': settings.CONTENT_TYPE,
        'Authorization': settings.AUTHORIZATION
    }

    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(settings.EXTERNAL_VOICE_LIST_URL, headers=headers, timeout=30) as response:
                response_data = await response.json()
                logging.info(f"外部 API 获取声音列表 响应：{response_data}")
                return response_data, response.status
        except aiohttp.ClientError as e:
            logging.error(f"请求声音列表接口异常：{e}")
            return {'error': f'Request exception occurred: {e}'}, 500
        except asyncio.TimeoutError:
            logging.error("请求声音列表接口超时")
            return {'error': 'Request timed out'}, 504

async def task_token():
    url = settings.TOKEN_REPORT
    # url = "https://hwserver.luzhuofun.com:3009/login"
    payload = {
        "acc": "17882216223",
        "psw": "123456"
    }
    headers = {
        'Content-Type': 'application/json',
    }
    # print(f"Attempting to connect to: {url}")
    # print(f"Sending payload: {payload}")  # 打印发送的数据
    
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, headers=headers, json=payload) as response:
                # print(f"Response status: {response.status}")
                if response.status == 200:
                    response_data = await response.json()
                    # print(f"Response data: {response_data}")
                    token = response_data.get('res', {}).get('__token')
                    if token:
                        return {"code": 200, "token": token}
                else:
                    error_text = await response.text()
                    print(f"Error response: {error_text}")
                return {"code": response.status}
        except Exception as e:
            logging.error(f"task_token 请求异常：{e}")
            print(f"Exception occurred: {e}")
            return {"code": 500}

async def task_report(verify_taskId, job_id):
    """
    上报积分使用
    """
    url = settings.REPORT
    print("verify_taskId：", verify_taskId)
    print("job_id:", job_id)
    
    token_response = await task_token()
    token = token_response.get("token", "")
    print("token:", token)
    
    headers = {
        'token': token,
        'Content-Type': 'application/json'
    }
    payload = {
        "reason": "创建视频",
        "action": "用户",
        "source": "优速",
        "taskId": verify_taskId,
        "jobId": str(job_id),
        "jobType": 0
    }
    
    print(f"Sending report payload: {payload}")
    
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, headers=headers, json=payload) as response:
                print(f"Report response status: {response.status}")
                if response.status != 200:
                    error_text = await response.text()
                    print(f"Error response: {error_text}")
                if response.status == 200:
                    return {"code": 200}
                return {"code": response.status}
        except Exception as e:
            logging.error(f"task_report 请求异常：{e}")
            return {"code": 500}
        



